package kin.converter;

import java.lang.reflect.Array;
import java.util.ArrayList;   
import java.util.Collection;
import java.util.List;  

import kin.system.util.ApplicationContextHelper;
import kin.system.util.StringUtil;

import org.apache.commons.beanutils.BeanUtils;  
import org.apache.commons.beanutils.BeanUtilsBean2;
import org.apache.commons.beanutils.ConversionException;  
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.MethodUtils;
import org.springframework.util.CollectionUtils;  
  

public final class CollectionTypeConverter implements ParameterizedTypeConverter {
   
    
    public Object convert(Class targetClass, Class destGenericType,Object origValue) {  
    	//System.out.println("destGenericType:"+targetClass.getInterfaces()[0].getSimpleName());
    	
        if(targetClass.getInterfaces()[0]==Collection.class){
        	
        
        String[] ov=  (String[]) origValue;
        if(destGenericType.getPackage().getName().equals("kin.bean.system")||destGenericType.getPackage().getName().equals("kin.test")||destGenericType.getPackage().getName().equals("kin.bean.coustomer")||destGenericType.getPackage().getName().equals("kin.bean.security")){
        if (ov.length>0 ){  
           
                List model = new ArrayList();  
                try {  
                    for (String s : ov) {
                    	
                    	int id=Integer.parseInt(s);
                    	String className=StringUtil.fristLetterLowerCase(destGenericType.getSimpleName());
                    	Object obj=ApplicationContextHelper.getBean(className+"ServiceManagerIMP");

                        Object dest = destGenericType.newInstance(); 
                      Object t= MethodUtils.invokeMethod(obj, "load", id);
                      
                        BeanUtils.copyProperty(dest, className+"_id", id);
                        model.add(dest);  
                    }  
                } catch (Exception e) {  
                    throw new ConversionException(e);  
                }  
                return model;  
            }  
       }
    }
        
        return origValue;  
    }

	public Object convert(Class arg0, Object arg1) {
		// TODO Auto-generated method stub
		return null;
	}  
}  
